package com.xuecheng.media.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.MediaDto;
import com.xuecheng.commons.model.dto.MediaQueryDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.VodUploadDto;
import com.xuecheng.commons.model.vo.MediaVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.VodUploadVo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.po.Media;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;

import java.awt.print.PageFormat;
import java.time.LocalDateTime;
import java.util.List;

public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate vodTemplate;

    @Override
    public ResponseResult<VodUploadVo> vodToken(VodUploadDto dto) {
        //1.参数校验
        if(StrUtil.isEmpty(dto.getFileName()) || StrUtil.isEmpty(dto.getTitle())){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        try {
            //2.获取上传凭证
            CreateUploadVideoResponse response = vodTemplate.createUploadVideo(dto.getTitle(), dto.getFileName());
            //3.转vo
            VodUploadVo vo = BeanHelper.copyProperties(response, VodUploadVo.class);
            //4.返回vo
            return ResponseResult.okResult(vo);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.ALIYUNERROR);
        }
    }

    /*
    * 刷新上传凭证
    * */
    @Override
    public ResponseResult<VodUploadVo> refreshVodToken(String videoId) {
        //1.参数校验
        if(StrUtil.isEmpty(videoId)){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        try {
            //2.刷新token
            RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
            //3.转vo
            VodUploadVo vo = BeanHelper.copyProperties(response, VodUploadVo.class);
            //4.返回vo
            return ResponseResult.okResult(vo);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.ALIYUNERROR);
        }
    }

    /*
    * 保存媒资
    * */
    @Override
    public ResponseResult saveMedia(MediaDto dto) throws ClientException {
        //1.校验参数
        if(StrUtil.isEmpty(dto.getFilename())|| StrUtil.isEmpty(dto.getFileId())){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //2.dto转实体
        Media media = BeanHelper.copyProperties(dto, Media.class);
        //3.根据视频id获取播放地址和时长
        GetPlayInfoResponse response = vodTemplate.getplayInfo(media.getFileId());
        //3-1 时长 91.1
        String duration = response.getPlayInfoList().get(0).getDefinition();
        //3-2 地址
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        //4.补充media信息
        media.setUrl(playURL);//播放地址
        //视频时长 91.1 -> 01:31
        Float f = Float.parseFloat(duration);
        LocalDateTime localTime = LocalDateTime.MIN.plusMinutes(f.longValue());
        media.setTimelength(localTime.toString());

        media.setUsername(AuthInfoHolder.getUserId().toString());//上传人
        media.setCreateDate(LocalDateTime.now());
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS);//审核状态
        //5.保存数据库
        this.save(media);
        //6.返回ok
        return ResponseResult.okResult();
    }

    /*
    * 媒资分页查询
    * */
    @Override
    public ResponseResult<MediaVo> findByPage(PageRequest pageRequest, MediaQueryDto dto) {
        //1.构建分页
        Page<Media> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        //2.条件分页查询
       page= this.lambdaQuery()
            .like(StrUtil.isNotEmpty(dto.getFilename()),Media::getFilename,dto.getFilename())
               .eq(StrUtil.isNotEmpty(dto.getType()),Media::getType,dto.getType())
               .eq(StrUtil.isNotEmpty(dto.getAuditStatus()),Media::getAuditStatus,dto.getAuditStatus())
               .page(page);
       //3.media转vo
        List<Media> mediaList = page.getRecords();
        List<MediaVo> voList = BeanHelper.copyWithCollection(mediaList, MediaVo.class);
        //4.返回分页
        return PageResponseResult.okResult(page.getTotal(),voList);
    }

    /*
    * 媒资预览
    * */
    @Override
    public ResponseResult<String> preview(Long mediaId) throws ClientException {
        //1.查询媒资对象
        Media media = this.getById(mediaId);
        //2.根据视频id查询最新播放地址
        GetPlayInfoResponse response = vodTemplate.getplayInfo(media.getFileId());
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        //3.返回播放地址
        return ResponseResult.okResult(playURL);
    }

    /*
    * 媒资删除
    * */
    @Override
    public ResponseResult deleteMedia(Long mediaId) throws ClientException {
        //1.查询媒资对象
        Media media = this.getById(mediaId);
        //2. 判断审核状态
        if(media.getAuditStatus().equals(MediaConstants.AUDIT_PASTED_STATUS)){
            //审核不通过
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //3.删除阿里云
        vodTemplate.deleteVideo(media.getFileId());
        //4.删除数据库
        this.removeById(mediaId);
        //5.返回ok
        return ResponseResult.okResult();
    }
}
